package com.weixin.converter;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.weixin.dto.OrderDto;
import com.weixin.enums.ResultEnum;
import com.weixin.exception.SellException;
import com.weixin.form.OrderForm;
import com.weixin.pojo.OrderDetail;
import com.weixin.pojo.OrderMaster;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author CJunGod
 * @create 2020-03-01 21:46
 **/
@Slf4j
public class OrderForm2OrderDtoConverter {

    public static OrderDto convert(OrderForm orderForm){
        Gson gson = new Gson();
        OrderDto orderDto = new OrderDto();
        OrderMaster orderMaster = new OrderMaster();
        orderMaster.setBuyerName(orderForm.getName());
        orderMaster.setBuyerPhone(orderForm.getPhone());
        orderMaster.setBuyerAddress(orderForm.getAddress());
        orderMaster.setBuyerOpenid(orderForm.getOpenid());

        orderDto.setMaster(orderMaster);

        List<OrderDetail> orderDetails = new ArrayList<>();
        try {
            orderDetails = gson.fromJson(orderForm.getItems(),
                    new TypeToken<List<OrderDetail>>(){}.getType());
        }catch (Exception e){
            log.error("{对象转换错误}，String={}",orderForm.getItems());
            throw new SellException(ResultEnum.PARAM_ERROR);
        }
        orderDto.setOrderDetailList(orderDetails);

        return orderDto;
    }
}
